<?php

namespace App\Server\Wxapp;

use Illuminate\Support\Facades\Redis;

class AccessToken
{
    private $cacheKey = "StrEx_access_token";

    public function get()
    {
        return Redis::get($this->cacheKey) ?: $this->remoteGet();
    }

    public function remoteGet()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $params = [
            'appid' => env("Wxapp_appid"),
            'secret' => env("Wxapp_secret"),
            'grant_type' => 'client_credential',
        ];
        $request = new \App\Server\Request\WxRequest;      
        ['access_token' => $accessToken, 'expires_in' => $ttl] = $request->fetchApi($url, $params);
        Redis::setEx($this->cacheKey, $ttl, $accessToken);
        return $accessToken;
    }

}